package com.dragon.app.thread;

public class ProductorConsumer {

	public static void main(String[] args) {
		Clerk clerk = new Clerk();
		
		new Thread(new Productor(clerk),"product-A").start();
		new Thread(new Consumer(clerk),"consumer-B").start();
		new Thread(new Consumer(clerk),"consumer-C").start();
		

	}
	
	
	static class Clerk{
		int product = 5;
		
		
		//记住，wait()外面一定要有synchronized，获得监视器；
		//还要有while来做条件判断，因为线程醒了之后不一定满足条件。防止虚假唤醒
		public void recieve() {
			synchronized (this) {
				while (product >= 20) {
					try {
						this.wait();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				product++;
				System.out.println(Thread.currentThread().getName() + ":生产了第" + product + "个商品。。");
				this.notifyAll();
			}
		}
		
		public void sale() {
			synchronized (this) {
				while (product <= 0) {
					try {
						this.wait();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				System.out.println(Thread.currentThread().getName() + "：消费了第" + product + "个商品。。");
				product--;
				this.notifyAll();
			}
		}
	}
	
	
	static class Productor implements Runnable{
		Clerk clerk;
		
		public Productor() {
			super();
		}

		public Productor(Clerk clerk) {
			super();
			this.clerk = clerk;
		}

		@Override
		public void run() {
			while(true) {
				clerk.recieve();
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	
	
	static class Consumer implements Runnable{
		Clerk clerk;

		public Consumer() {
			super();
		}

		public Consumer(Clerk clerk) {
			super();
			this.clerk = clerk;
		}

		@Override
		public void run() {
			while(true) {
				clerk.sale();
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	

}
